package com.yiyihealth.cherriesadmin.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.yiyihealth.cherriesadmin.core.http.HttpResult;
import com.yiyihealth.cherriesadmin.core.web.BaseController;
import com.yiyihealth.cherriesadmin.model.*;
import com.yiyihealth.cherriesadmin.model.wrapper.OrdSchedulingTemplateWrapper;
import com.yiyihealth.cherriesadmin.service.OrdSchedulingService;
import com.yiyihealth.cherriesadmin.service.OrdSchedulingTemplateService;
import com.yiyihealth.cherriesadmin.service.PubBindInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.ChronoLocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 排版模板(OrdSchedulingTemplate)表控制层
 *
 * @author chen
 * @since 2020-09-25 11:00:32
 */
@Api(tags = "排版模板类")
@RestController
@RequestMapping("ordSchedulingTemplate")
public class OrdSchedulingTemplateController extends BaseController<OrdSchedulingTemplate, OrdSchedulingTemplateWrapper, Long> {
    /**
     * 服务对象
     */
    @Resource
    private OrdSchedulingTemplateService ordSchedulingTemplateService;
    @Resource
    private OrdSchedulingService schedulingService;
    @Resource
    private PubBindInfoService pubBindInfoService;
    @Resource
    private RedisTemplate<Object, Object> redisCacheTemplate;

    @Override
    @InitBinder()
    public void initBinder(WebDataBinder binder) {
        super.setBaseService(ordSchedulingTemplateService);
    }

    /**
     * 根据模板生成临时排班接口
     * @param id
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据模板生成临时排班接口")
    @ApiImplicitParam(name = "id",value = "主键id",required = true)
    @PostMapping("/createScheduling")
    @ResponseBody
    public HttpResult createScheduling(Long id) throws Exception {
        OrdSchedulingTemplate ordSchedulingTemplate = ordSchedulingTemplateService.selectByPrimaryKey(Long.valueOf(id));
        String result=ordSchedulingTemplateService.createScheduling(ordSchedulingTemplate,null);
        redisCacheTemplate.delete("options::0");
        redisCacheTemplate.delete("options::57170");
        redisCacheTemplate.delete("options::57171");
        redisCacheTemplate.delete("options::57172");
        schedulingService.selectListForOptions(0L);
        schedulingService.selectListForOptions(57170L);
        schedulingService.selectListForOptions(57171L);
        schedulingService.selectListForOptions(57172L);
        return HttpResult.success(result);
    }

    /**
     * 根据模板生成临时排班接口
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据模板生成临时排班接口")
    @ApiImplicitParam(name = "id",value = "主键id",required = true)
    @PostMapping("/createSchedulingBatch")
    @ResponseBody
    public HttpResult createSchedulingBatch(@RequestParam Long doctorId) throws Exception {
        return HttpResult.success(ordSchedulingTemplateService.createSchedulingBatch(doctorId));
    }

    /**
     * 根据模板生成临时排班接口
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据模板生成临时排班接口")
    @ApiImplicitParam(name = "id",value = "主键id",required = true)
    @PostMapping("/createSchedulingBatchAll")
    @ResponseBody
    public HttpResult createSchedulingBatchAll() throws Exception {
        return HttpResult.success(ordSchedulingTemplateService.createSchedulingBatch());
    }

    @ApiOperation(value = "H5根据用户信息查询预约记录")
    @GetMapping("/week")
    @ResponseBody
    public HttpResult week() throws Exception {
        return HttpResult.success(DateUtil.weekOfYear(DateUtil.date(LocalDate.now())));
    }

    @Override
    public HttpResult create(@RequestBody OrdSchedulingTemplate record) throws Exception {
        return super.create(record);
    }

    @Override
    public HttpResult updateByPrimaryKeySelective(@RequestBody OrdSchedulingTemplate record)  {
        long num = ChronoUnit.MINUTES.between(record.getStartTime(),record.getEndTime());
        record.setAverageVisitTime(Integer.valueOf((int) (num/record.getAmount())));
        OrdSchedulingTemplate ordSchedulingTemplate = ordSchedulingTemplateService.updateByPrimaryKeySelective(fillInRedundantFields(record));
        Map<String, Object> map = new HashMap<String, Object>(8);
        map.put("templateId", record.getId());
        List<OrdScheduling> ordSchedulingList = schedulingService.selectList(map);
        for (OrdScheduling ordScheduling:ordSchedulingList){
            ordScheduling.setDoctorPracticeScope(record.getDoctorPracticeScope());
            ordScheduling.setRegistrationFee(record.getRegistrationFee());
            schedulingService.updateByPrimaryKeySelective(ordScheduling);
        }
        return HttpResult.success(ordSchedulingTemplate);
    }

    @RequestMapping("/extractHisData")
    @ResponseBody
    public HttpResult extractHisData() throws Exception {
        String res="获取排班信息成功!";
        try {
            res=ordSchedulingTemplateService.ExtractHisData();
        }catch (Exception e){
            throw new Exception(e.getMessage());
        }
        return HttpResult.success(res);
    }

    /**
     * 填充冗余字段信息
     * @param record
     * @return
     */
    private OrdSchedulingTemplate fillInRedundantFields(OrdSchedulingTemplate record){
        if (Optional.ofNullable(record.getDepName()).isPresent()){
            String redisKey = "departments:"+record.getHospitalId()+":"+record.getDepId();
            if (redisCacheTemplate.hasKey(redisKey)){
                PubDepartments departments = (PubDepartments) redisCacheTemplate.opsForValue().get(redisKey);
                record.setDepName(departments.getDepName());
            }
        }
        if (Optional.ofNullable(record.getBinName()).isPresent()){
            PubBindInfo bindInfo = pubBindInfoService.selectByPrimaryKey(record.getBinId());
            record.setBinName(bindInfo.getBinName());
        }
        if (!Optional.ofNullable(record.getDoctorName()).isPresent()){
            String redisKey = "doctor:"+record.getHospitalId()+":"+record.getDoctorId();
            if (redisCacheTemplate.hasKey(redisKey)){
                PubDoctor doctor = (PubDoctor) redisCacheTemplate.opsForValue().get(redisKey);
                record.setDoctorName(doctor.getDoctorName());
            }
        }
        if (!Optional.ofNullable(record.getStatus()).isPresent()){
            record.setStatus("0");
        }
        return record;
    }
}
